package com.SFA.Main;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;


import org.apache.http.client.ClientProtocolException;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.os.StatFs;

/**
 * 工具类
 * 
 * @author lushan.wang
 * 
 */
public class MyUtil
{

	/***
	 * 保存新闻列表的
	 */
	public static void saveLastRefreshTime(Context context, long date)
	{
		Calendar time = Calendar.getInstance();
		time.setTimeInMillis(date);
		int Month = time.get(Calendar.MONTH);
		int day = time.get(Calendar.DAY_OF_MONTH);
		int HH = time.get(Calendar.HOUR_OF_DAY);
		int MM = time.get(Calendar.MINUTE);
		String string = time.get(Calendar.YEAR)
				+ "年"
				+ Month
				+ "月"
				+ day
				+ "日 "
				+ HH
				+ ":"
				+ MM;

		context.getSharedPreferences("login", Context.MODE_PRIVATE)
		.edit()
		.putString("time", string)
		.commit();

	}

	/***
	 * 获取新闻列表更新时间
	 */
	public static String getLastRefreshTime(Context context)
	{
		return context.getSharedPreferences("login", Context.MODE_PRIVATE)
				.getString("time", null);
	}

	/****
	 * 获取图片的正式地址 ,DanaInfo=home.com.com,Port=800+
	 * infospace/topicnews/glts/zyxw/PublishingImages/解决方案也是领导力.JPG
	 */
	public static String getImageURL(String url)
	{
		if (url.contains("DanaInfo"))
		{
			return url;
		}
		int NameIndex = url.lastIndexOf("/") + 1;
		String urlPart = url.substring(0, NameIndex);
		String ImageName = url.substring(NameIndex);
		String Temp = ",DanaInfo=%1$s,Port=%2$s+";
		Temp = String.format(Temp, "home.com.com", "800");

		return urlPart + "/" + Temp + ImageName;

	}

	/***
	 * 获取当前AD用户(审批路径)
	 * 
	 */
	public static String getADuser(Context context)
	{
		return "com\\"
				+ context.getSharedPreferences("login", Context.MODE_PRIVATE)
				.getString("LastUser", "");
	}

	/***
	 * 
	 * @param inputStream
	 * @return 把流转化为字符串
	 * @throws Exception
	 */
	public static String readContents(InputStream inputStream) throws Exception
	{
		BufferedReader in = null;
		StringBuffer sb = new StringBuffer();
		in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));

		String inputLine;
		while ((inputLine = in.readLine()) != null)
		{
			sb.append(inputLine);
			sb.append("\n");
		}
		return sb.toString();
	}

	/***
	 * 时间格式转换
	 */
	public static String convertTime(String time)
	{
		// 如果时间后缀为Z的要转换成GMT
		if (time.contains("Z"))
		{
			time = time.replace("Z", "GMT");
		}
		Long date = Date.parse(time);
		Date date2 = new Date(date);
		SimpleDateFormat simpleDateFormat = null;
		simpleDateFormat = new SimpleDateFormat("yyyy年 MM月dd日 hh:mm");
		return simpleDateFormat.format(date2);
	}

	public static Bitmap toRoundCorner(Bitmap bitmap, int pixels)
	{
		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
				bitmap.getHeight(),
				Config.ARGB_8888);
		Canvas canvas = new Canvas(output);
		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
		final RectF rectF = new RectF(rect);
		final float roundPx = pixels;
		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);
		return output;
	}

	public static Bitmap drawableToBitmap(Drawable drawable)
	{

		Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
				drawable.getIntrinsicHeight(),
				drawable.getOpacity() != PixelFormat.OPAQUE
				? Bitmap.Config.ARGB_8888
						: Bitmap.Config.RGB_565);
		Canvas canvas = new Canvas(bitmap);
		// canvas.setBitmap(bitmap);
		drawable.setBounds(0,
				0,
				drawable.getIntrinsicWidth(),
				drawable.getIntrinsicHeight());
		drawable.draw(canvas);
		return bitmap;
	}

	/** * 计算sdcard上的剩余空间 * @return */
	private static int freeSpaceOnSd()
	{
		StatFs stat = new StatFs(Environment.getExternalStorageDirectory()
				.getPath());
		double sdFreeMB = ((double) stat.getAvailableBlocks() * (double) stat.getBlockSize())
				/ MB;

		return (int) sdFreeMB;
	}

	private static int	 FREE_SD_SPACE_NEEDED_TO_CACHE = 1;
	private static int	 MB			    = 1024 * 1024;
	public final static String DIR			   = "/sdcard/com/";

	public static String BuildFilePath(String url)
	{
		String LOCALURL = url;// URLEncoder.encode(url);
		return DIR + "/" + LOCALURL;

	}

	public static boolean Exist(String url)
	{
		File file = new File(url);
		return file.exists();

	}

	public static Bitmap GetBitmap(String url, int quantity)
	{
		Bitmap map = null;
		if (url == null)
			return null;
		String filename = "";
		try
		{
			filename = url.substring(url.indexOf("+") + 1);
		}
		catch (Exception err)
		{
		}

		String LOCALURL = filename;// URLEncoder.encode(filename);
		if (Exist(DIR + "/" + LOCALURL))
		{
			map = BitmapFactory.decodeFile(DIR + "/" + LOCALURL);

		}
		else
		{
			try
			{
				// url = URLEncoder.encode(url, "UTF-8");
				map = HttpFactory.HttpFactorys.GetInputStream(url);
				if (map != null)
				{
					saveBmpToSd(map, LOCALURL, quantity);
				}
			}
			catch (ClientProtocolException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			catch (Exception e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return map;
	}

	public static void saveBmpToSd(Bitmap bm, String url, int quantity)
	{

		if (bm == null)
		{
			return;
		}
		// 判断sdcard上的空间
		if (FREE_SD_SPACE_NEEDED_TO_CACHE > freeSpaceOnSd())
		{
			return;
		}
		if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()))
			return;
		String filename = url;
		// 目录不存在就创建
		File dirPath = new File(DIR);
		if (!dirPath.exists())
		{
			dirPath.mkdirs();
		}

		File file = new File(DIR + "/" + filename);
		try
		{
			file.createNewFile();
			OutputStream outStream = new FileOutputStream(file);
			bm.compress(Bitmap.CompressFormat.PNG, quantity, outStream);
			outStream.flush();
			outStream.close();

		}
		catch (FileNotFoundException e)
		{

		}
		catch (IOException e)
		{
			e.printStackTrace();
		}

	}

	/***
	 * 保存文件至SD卡
	 * 
	 * @param bm
	 * @param url
	 * @param quantity
	 */
	public static String
	savFilepToSd(InputStream inputStream, String file_name)
	{

		if (inputStream == null)
		{
			return null;
		}
		// 判断sdcard上的空间
		if (FREE_SD_SPACE_NEEDED_TO_CACHE > freeSpaceOnSd())
		{
			return null;
		}
		if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()))
			return null;
		String filename = file_name;
		// 目录不存在就创建
		File dirPath = new File(DIR);
		if (!dirPath.exists())
		{
			dirPath.mkdir();
		}

		File file = new File(DIR + "/" + filename);

		// // 存在返回此文件
		// if (Exist(file.toString()))
		// {
		// return file.toString();
		// }

		try
		{
			file.createNewFile();
			OutputStream outStream = new FileOutputStream(file);

			byte buf[] = new byte[128];
			int byteRead = -1;
			while ((byteRead = (inputStream.read(buf))) != -1)
			{
				outStream.write(buf, 0, byteRead);
			}
			outStream.flush();
			outStream.close();

			return file.toString();
		}
		catch (FileNotFoundException e)
		{
			return null;
		}
		catch (IOException e)
		{
			return null;
		}

	}

	/***
	 * 产生一个10以内的随机整数
	 */
	public static int getRandom()
	{
		return new Random().nextInt(20) + 1;
	}

}
